package cn.zjjd.wlproject.hhx.demo.controller;

import cn.zjjd.wlproject.hhx.demo.config.DateUtil;
import cn.zjjd.wlproject.hhx.demo.config.ExcelUtil;
import cn.zjjd.wlproject.hhx.demo.config.FileUtil;
import cn.zjjd.wlproject.hhx.demo.config.ResponseUtil;
import cn.zjjd.wlproject.hhx.demo.pojo.Student;
import cn.zjjd.wlproject.hhx.demo.service.StudentService;
import cn.zjjd.wlproject.hhx.demo.util.GeneralResponse;
import net.minidev.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;


    @GetMapping("/queryStudentList")
    public GeneralResponse queryStudentList(){
        GeneralResponse response = new GeneralResponse();
        response.setSuccess(true);
        response.setData(studentService.queryStudentList());
        return response;
    }
    @GetMapping("/queryStudentByNumber")
    public GeneralResponse queryStudentByNumber(@RequestParam int number){
        GeneralResponse response = new GeneralResponse();
        response.setSuccess(true);
        List<Student> result = new ArrayList<>();
        result.add(studentService.queryStudentByNumber(number));
        response.setData(result);
        return  response;
    }

    @PostMapping("/addStudent")
    public GeneralResponse addStudent(@RequestParam int number,@RequestParam String name,@RequestParam String classname,@RequestParam String phone,HttpSession session){
        GeneralResponse response = new GeneralResponse();
        if((int)session.getAttribute("rightgrade") == 1){
            Student student = new Student();
            student.setNumber(number);
            student.setName(name);
            student.setClassname(classname);
            student.setPhone(phone);
            response.setSuccess(true);
            response.setData(studentService.addStudent(student));
            return  response;
        }
        else{
            response.setSuccess(false);
            response.setData("您没有这个权限");
            return  response;
        }

    }

    @PutMapping("/updateStudent")
    public GeneralResponse updateStudent(@RequestParam int id,@RequestParam int number,@RequestParam String name,@RequestParam String classname,@RequestParam String phone,HttpSession session){
        GeneralResponse response = new GeneralResponse();
        if((int)session.getAttribute("rightgrade") == 1){
        Student student = new Student();
        student.setId(id);
        student.setNumber(number);
        student.setName(name);
        student.setClassname(classname);
        student.setPhone(phone);
        response.setSuccess(true);
        response.setData(studentService.updateStudent(student));
        return  response;
        }
        else{
            response.setSuccess(false);
            response.setData("您没有这个权限");
            return  response;
        }
    }

    @PostMapping("/deleteStudent")
    public GeneralResponse deleteStudent(@RequestParam int id,HttpSession session){
        GeneralResponse response = new GeneralResponse();
        if((int)session.getAttribute("rightgrade") == 1) {
            response.setSuccess(true);
            response.setData(studentService.deleteStudent(id));
            return response;
        }
        else{
            response.setSuccess(false);
            response.setData("您没有这个权限");
            return  response;
        }
    }

    /**
     *   接受文件   解析  上传资料。
     *   /admin/client/upload_excel
     */
    @ResponseBody
    @RequestMapping("/upload_excel")
    public JSONObject upload_excel(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request)throws Exception {
        JSONObject result = new JSONObject();

        System.out.println(file.getOriginalFilename());
        List<Student> list = null;
        if(!file.isEmpty()){
            String webPath=request.getServletContext().getRealPath("");
            String filePath= "/static/upload_file/excel/";
            //把文件名子换成（时间搓.png）
            // String imageName="houtai_logo."+file.getOriginalFilename().split("\\.")[1];
            String fileName= DateUtil.formatDate(new Date(), "yyyyMMdd-HHmmssSSS")+"_"+file.getOriginalFilename();

            FileUtil.makeDirs(webPath+filePath);
            //保存服务器
            file.transferTo(new File(webPath+filePath+fileName));
            //保存服务器

            //解析
            list =  excel_to_clientInfo(new File(webPath+filePath+fileName));
            //解析

            //开始 上传 数据库
            for(Student student:list) {
                studentService.addStudent(student);
            }
            //开始 上传 数据库

            //删除用过的文件
            FileUtil.deleteFile(webPath+filePath+fileName);
            //删除用过的文件
        }
        result.put("success", true);
        result.put("msg", "导入成功");
        result.put("list",list);
        return result;
    }

    private List<Student> excel_to_clientInfo(File userUploadFile) throws ParseException {
        List<Student> list = new ArrayList<Student>();
        Student student = null;
        try {
            POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(userUploadFile));
            HSSFWorkbook wb = new HSSFWorkbook(fs);
            //获取第一个sheet页
            HSSFSheet sheet = wb.getSheetAt(0);
            if(sheet!=null){
                for(int rowNum =1;rowNum<=sheet.getLastRowNum();rowNum++){
                    HSSFRow row = sheet.getRow(rowNum);
                    if(row==null){
                        continue;
                    }
                    student  =new Student();
                    //去掉编码中的  .0 如果全是数字 后面有.0
                    String number =ExcelUtil.formatCell(row.getCell(1));
                    student.setNumber(Integer.parseInt(number));
                    student.setName(ExcelUtil.formatCell(row.getCell(2)));
                    student.setClassname(ExcelUtil.formatCell(row.getCell(3)));
                    student.setPhone(ExcelUtil.formatCell(row.getCell(4)));
                    list.add(student);
                }
            }
        }  catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    @RequestMapping("/exceldown")
    public String exceldown(HttpServletResponse response) throws Exception{
        ClassPathResource resource = new ClassPathResource("");
        String webPath = resource.getFile().getAbsolutePath();
        List<Student> list = studentService.queryStudentList();
        Workbook wb = fillExcelDataWithTemplate(list,webPath+"/static/client_down_model.xls");
        ResponseUtil.export(response,wb,"学生.xls");
        return  null;
    }


    public static Workbook fillExcelDataWithTemplate(List<Student> list ,String templateFileUrl) {

        Workbook wb = null ;
        try {
            POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(templateFileUrl));
            wb = new HSSFWorkbook(fs);
            // 取得 模板的 第一个sheet 页
            Sheet sheet = wb.getSheetAt(0);
            // 拿到sheet页有 多少列
            int cellNums = sheet.getRow(0).getLastCellNum();
            // 从第2行 开搞    下标1  就是第2行
            int rowIndex = 1;
            Row row ;
            for(Student student : list){
                row = sheet.createRow(rowIndex);
                rowIndex ++;
                row.createCell(0).setCellValue(student.getId());

                row.createCell(1).setCellValue(student.getNumber());
                row.createCell(2).setCellValue(student.getName());
                row.createCell(3).setCellValue(student.getClassname());
                row.createCell(4).setCellValue(student.getPhone());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    private void downloadFile(HttpServletResponse response, String path, String fileName) throws IOException {
        /** 将文件名称进行编码 */
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("content-type:octet-stream");
        /** 读取服务器端模板文件 */
        InputStream inputStream = this.getClass().getResourceAsStream(path);

        /** 将流中内容写出去 */
        OutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
        outputStream.close();
    }
}
